// 按期降赔组件模板
<template>
  <div class="app-container">
    <div style="margin-bottom:10px;" v-if="catalogList">
      <el-table :data="catalogList" v-loading="loading" key="catalogTable" :cell-class-name="CatalogCellClass" header-cell-class-name='tableHeader' element-loading-text="加载中" border fit>
        <el-table-column prop="" label="种类" align="center" min-width="150">
          <template slot-scope="scope">{{scope.row.category_name}}</template>
        </el-table-column>
        <!-- <el-table-column prop="" label="" align="center" width="10"> </el-table-column> -->

        <!-- 根据返回的colMap动态生成列  开始 -->
        <el-table-column v-for="(item,key) in colMap" :key="`settingCatalogProp${key}`" :label="item.showName" align="center" min-width="80">
          <template slot-scope="scope">
            <!-- 根据字段不同的key值添加不同的样式 -->
            <span v-if="item.field === 'period'">{{scope.row[item.field]}}</span>
            <el-input-number v-else :class="`${scope.row[`${item.field}_highlight_class`]}`" size="mini" :min=item.min :max=item.max :step=item.step v-model="scope.row[item.field]" @change="catalogInputChange(item.field,scope.$index,scope.row)">
            </el-input-number>
          </template>
        </el-table-column>
        <!-- 根据返回的colMap动态生成列  结束 -->

      </el-table>
    </div>
    <el-tabs v-if="list" type="border-card" v-model="game_code" tab-position="left">
      <el-tab-pane v-for="(item) in games" :key="`gameid${item.entity_id}`" :name="item.game_code" :label="item.name">
        <el-table :data="list[item.game_code]" v-loading="loading" key="listTable" :cell-class-name="CatalogCellClass" header-cell-class-name='tableHeader' element-loading-text="加载中" border fit stripe>
          <!-- <el-table-column type="index" label="#" align="center" min-width="35">
          </el-table-column> -->

          <!-- <el-table-column prop="" label="" align="center" width="10"> </el-table-column> -->

          <!-- 根据返回的colMap动态生成列  开始 -->
          <el-table-column v-for="(item,key) in colMap" :key="`settingListProp${key}`" :label="item.showName" align="center" min-width="80">
            <template slot-scope="scope">
              <span v-if="item.field === 'period'">{{scope.row[item.field]}}期</span>
              <el-input-number v-else :class="`${scope.row[`${item.field}_highlight_class`]}`" size="mini" :min=item.min :max=item.max :step=item.step v-model="scope.row[item.field]" @change="cellChange(item.field,scope.$index,scope.row)"></el-input-number>
            </template>
          </el-table-column>
          <!-- 根据返回的colMap动态生成列  结束 -->
        </el-table>
        <el-row class="btn-group-submit">
          <el-button @click="getSetting">重置</el-button>
          <el-button type="primary" :loading="loading" @click.native.prevent="onSubmit">修改</el-button>
          <el-button @click="getSetting">刷新</el-button>
        </el-row>
      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { formatFloat } from '@/utils/index'
import { user as userMap } from '@/utils/map' // 参数映射

export default {
  name: 'SettingPeriod',
  props: ['colMap', 'dispatchName', 'listName'],
  data() {
    return {
      params: {}, // 要提交保存的表单
      loading: false,
      catalogList: null, // 提成分类列表数据源  array
      list: null, // 详细表格数据源  array
      game_code: null, // 以game_code作为tab的key
      userMap: userMap, // 用户字段映射
    }
  },
  filters: {
    formatFloat: formatFloat, // 格式化保留两位小数,
  },
  created() {
    this.game_code = this.games[0].game_code
    this.getSetting()
  },
  computed: {
    ...mapGetters(['games', 'handicaps', 'category']),
  },
  methods: {
    // 获取父级commission设置
    getSetting() {
      this.loading = true
      this.$store.dispatch(this.dispatchName.get, {}).then(response => {
        this.loading = false
        if (response) {
          // 格式化目录数据列表
          this.formatCatalog()

          // 格式化表格数据列表
          if (typeof this.listName === 'string') {
            this.formatList(response[this.listName])
          } else {
            this.formatList(response[this.listName[0]][this.listName[1]])
          }

          // 重置params参数
          this.params = {}
        }
      })
    },

    // 格式化头部目录
    formatCatalog() {
      const res = []
      for (const category_code in this.category) {
        if (this.category.hasOwnProperty(category_code)) {
          const item = this.category[category_code]
          const row = {}
          row['category_code'] = category_code
          row['category_name'] = this.userMap.gameCatalogCode[
            category_code
          ].name

          for (const key in this.colMap) {
            if (this.colMap.hasOwnProperty(key)) {
              const element = this.colMap[key]
              row[`${element.field}_highlight_class`] = '' // 根据k添加对应高亮样式
            }
          }

          res.push(row)
        }
      }

      // console.log(res)
      // this.catalogList = res
    },

    // 格式化列表
    formatList(defaultSetting) {
      const res = []
      for (const game_code in defaultSetting) {
        res[game_code] = []
        if (defaultSetting.hasOwnProperty(game_code)) {
          const game = defaultSetting[game_code]
          for (const item_code in game) {
            if (game.hasOwnProperty(item_code)) {
              const item = game[item_code]
              item['init'] = JSON.parse(JSON.stringify(item)) // 保存自身初始值 ,用于金额判断
              for (const key in this.colMap) {
                if (this.colMap.hasOwnProperty(key)) {
                  const element = this.colMap[key]
                  item[`${element.field}_highlight_class`] = '' // 根据k添加对应高亮样式
                }
              }
              res[game_code].push(item)
            }
          }
        }
      }
      // console.log(res)

      this.list = res
    },

    // 目录input变化 导致同catalogcode的input一起变化
    catalogInputChange(...args) {
      this.$nextTick(_ => {
        // console.log(args)

        // 获取回调后的值才是最新的值
        const [key_name, rowIndex, row] = args
        const valueInit = 0 // 初始值,
        const valueInput = row[key_name] // 输入值
        // 添加cattaloginput高亮样式
        if (valueInit !== valueInput) {
          this.catalogList[rowIndex][`${key_name}_highlight_class`] =
            'hightlight'
        } else {
          this.catalogList[rowIndex][`${key_name}_highlight_class`] = ''
        }

        // console.log(valueInput, valueMax, this.catalogList);
        for (const game_code in this.list) {
          if (this.list.hasOwnProperty(game_code)) {
            // 这里为什么要用hasOwnProperty进行过滤呢？
            // 因为for...in 循环会把对象原型链上的所有可枚举属性都循环出来
            const game = this.list[game_code]
            for (const i in game) {
              if (game.hasOwnProperty(i)) {
                const item = game[i]

                if (item.category_code === row.category_code) {
                  item[key_name] = valueInput // 根据目录输入,批量修改对应的表格值
                  // 添加高亮样式  与自身初始值不一致 ##最佳实现,与自身初始值对比
                  if (item.init[key_name] !== valueInput) {
                    item[`${key_name}_highlight_class`] = 'hightlight'

                    this.params[`${item.item_code}-${key_name}`] = item // 保存修改的item
                  } else {
                    // 删除样式
                    item[`${key_name}_highlight_class`] = ''
                    delete this.params[`${item.item_code}-${key_name}`] // 删除未修改行
                  }
                }
              }
            }
          }
        }
        // console.log(this.params, Object.keys(this.params).length);
      })
    },

    // 表格input的变化
    cellChange(...args) {
      this.$nextTick(_ => {
        // 获取回调后的值才是最新的值
        const [key_name, rowIndex, row] = args
        const valueInit = row.init[key_name] // 初始值,
        const valueInput = row[key_name] // 输入值
        if (parseFloat(valueInput) !== parseFloat(valueInit)) {
          // highlight
          row[`${key_name}_highlight_class`] = 'hightlight'
          // 保存修改的item
          this.params[`${row.reduce_item_code}-${key_name}`] = row
        } else {
          row[`${key_name}_highlight_class`] = ''
          delete this.params[`${row.reduce_item_code}-${key_name}`] // 删除未修改行
        }
        console.log(valueInit, valueInput)
        console.log(Object.keys(this.params).length)
      })
    },

    onSubmit() {
      // console.log(this.params);
      const ob = {}
      for (const k in this.params) {
        if (this.params.hasOwnProperty(k)) {
          const row = this.params[k]
          const [item_code, key_name] = k.split('-')

          if (typeof ob[item_code] === 'undefined') {
            ob[item_code] = {}
          }
          ob[item_code]['game_code'] = row.game_code
          ob[item_code]['item'] = row.item_code //* 注意: 这里与profile 下的 commission的参数不同
          ob[item_code][key_name] = row[key_name]
        }
      }
      // console.log(ob, Object.values(ob).length);
      const params = Object.values(ob)
      if (params.length <= 0) {
        // 没有修改
        this.$message({
          message: '没有金额变化的条目!',
          type: 'warning',
        })
      } else {
        this.loading = true
        this.$store
          .dispatch(this.dispatchName.set, {
            params: params,
          })
          .then(response => {
            this.loading = false
            if (response === true) {
              this.$alert('修改成功', '提示', {
                confirmButtonText: '确定',
                center: true,
                callback: this.getSetting,
              })
            } else {
              this.$message({
                message: '修改失败',
                type: 'warning',
              })
            }
          })
          .catch(error => {
            this.loading = false
            console.log(error)
            this.$message({
              message: error.message,
              type: 'warning',
            })
          })
      }
    },

    // 表格样式
    CatalogCellClass({ row, column, rowIndex, columnIndex }) {
      // if (columnIndex === 1) {
      //   return this.userMap.gameCatalogCode[row.category_code].className
      // }
      // console.log(row, column, rowIndex, columnIndex);
    },
  },
  watch: {},
}
</script>

<style>

</style>
